﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace OrderingPlatform.MvcExtension
{
    public static class FomatExtension
    {
        #region 数字
        public static string Format(this decimal? num, string formatString = "#0.00", string defaultValue = "")
        {
            return num.HasValue ? num.Value.ToString(formatString) : defaultValue;
        }

        public static string Format(this decimal num, string formatString = "#0.00")
        {
            return num.ToString(formatString);
        }

        public static string Format(this double num, string formatString = "#0.00")
        {
            return num.ToString(formatString);
        }

        public static string Format(this double? num, string formatString = "#0.00")
        {
            if (num == null) return "0.00";
            return num.Value.ToString(formatString);
        }

        public static string Format(this float num, string formatString = "#0.00")
        {
            return num.ToString(formatString);
        }
        public static string Format(this float? num, string formatString = "#0.00")
        {
            if (num == null) return "0.00";
            return num.Value.ToString(formatString);
        }
        #endregion

        #region 日期格式化
        /// <summary>
        /// 格式化日期
        /// </summary>
        /// <param name="date"></param>
        /// <param name="formatString"></param>
        /// <param name="defautString"></param>
        /// <returns></returns>
        public static string Format(this DateTime date, string formatString = "yyyy-MM-dd", string defautString = "-")
        {
            if (date.ToString(CultureInfo.InvariantCulture).Contains("0001-1-1"))
                return defautString;
            return date.ToString(formatString);
        }

        /// <summary>
        /// 格式化日期
        /// </summary>
        /// <param name="date"></param>
        /// <param name="formatString"></param>
        /// <param name="defautString"></param>
        /// <returns></returns>
        public static string Format(this DateTime? date, string formatString = "yyyy-MM-dd", string defautString = "-")
        {
            if (date.HasValue)
            {
                return date.Value.ToString(formatString);
            }

            return defautString;
        }

        public static string FormatAvoidDefault(this DateTime? date, string formatString = "yyyy-MM-dd")
        {
            if (date.HasValue && date.ToString() != "0001/1/1 0:00:00")
            {
                return date.Value.ToString(formatString);
            }

            return string.Empty;
        }

        /// <summary>
        /// <para> 功    能： 日期转换 </para>
        /// <para> 如果是当天，显示时间；如果是当年，显示月日，或者显示短日期类型</para>
        /// <para> 作    者： 韩保新 </para>
        /// <para> 创建日期： 2012-7-29</para>
        /// </summary>
        /// <param name="date"></param>
        /// <param name="defautString"></param>
        /// <returns></returns>
        public static string FormatDayTime(this DateTime date, string defautString = "")
        {
            var dt = DateTime.Now;

            if (date.Year == dt.Year)
            {
                return date.Day == dt.Day ? string.Format("{0}/{1}", date.Hour, date.Minute) : string.Format("{0}/{1}", date.Month, date.Day);
            }
            return date.ToString("yyyy-MM-dd");

        }
        /// <summary>
        /// <para> 功    能： 日期转换 </para>
        /// <para> 作    者： 韩保新 </para>
        /// <para> 创建日期： 2012-10-18</para>
        /// </summary>
        /// <param name="date"></param>
        /// <param name="isYear"></param>
        /// <returns></returns>
        public static string DateConvertDay(this DateTime? date, bool isYear = false)
        {
            if (date != null)
            {
                DateTime dt = Convert.ToDateTime(date.ToString());
                DateTime nowDate = DateTime.Now;
                if (dt.ToShortDateString() == nowDate.ToShortDateString())
                {
                    if (dt.Minute < 10)
                        return dt.Hour + ":0" + dt.Minute;
                    return dt.Hour + ":" + dt.Minute;
                }
                if (isYear)
                    return dt.Month + "-" + dt.Day;
                if (dt.Year == nowDate.Year)
                    return dt.Month + "-" + dt.Day;
                return Convert.ToDateTime(date.ToString()).ToString("yyyy-MM-dd");
            }
            return "";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="date"></param>
        /// <param name="isYear"></param>
        /// <returns></returns>
        public static string DateConvertDay(this DateTime date, bool isYear = false)
        {
            {
                var dt = Convert.ToDateTime(date.ToString(CultureInfo.InvariantCulture));
                var nowDate = DateTime.Now;
                if (dt.ToShortDateString() == nowDate.ToShortDateString())
                {
                    if (dt.Minute < 10)
                        return dt.Hour + ":0" + dt.Minute;
                    return dt.Hour + ":" + dt.Minute;
                }
                if (isYear)
                    return dt.Month + "-" + dt.Day;
                if (dt.Year == nowDate.Year)
                    return dt.Month + "-" + dt.Day;
                return Convert.ToDateTime(date.ToString(CultureInfo.InvariantCulture)).ToString("yyyy-MM-dd");
            }
        }

        /// <summary>
        /// 日期转时间
        /// </summary>
        /// <param name="date"></param>
        /// <param name="defaultString"></param>
        /// <returns></returns>
        public static string DateToHh(this DateTime? date, string defaultString = "-")
        {
            if (date == null)
                return defaultString;
            var d = date.Value;
            return string.Format("{0}:{1}:{2}", d.Hour, d.Minute, d.Second);
        }
        #endregion

        #region 字符串格式化
        /// <summary>
        /// <para> 功    能： 为空的字符串转成替代符合 </para>
        /// <para> 作    者： 韩保新 </para>
        /// <para> 创建日期： 2012-10-24</para>
        /// </summary>
        /// <param name="str"></param>
        /// <param name="mark"></param>
        /// <returns></returns>
        public static string Format(this String str, string mark = "-")
        {
            if (!string.IsNullOrEmpty(str))
            {
                if (!string.IsNullOrEmpty(str.Trim()))
                {
                    return str.Trim().Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
                }
            }
            return mark;
        }

        public static string Format(this string str, int length)
        {
            if (str.Length > length)
            {
                return str.Substring(0, length) + "...";
            }
            return str;
        }

        public static string FormatList(this List<string> list, string returnMark = "-", char fg = ';')
        {
            if (list == null || list.Count <= 0)
                return returnMark;
            var result = list.Aggregate("", (current, s) => current + (s + fg));
            result = result.TrimEnd(fg);//.Substring(0,result.LastIndexOf(';'));
            return result;
        }
        public static string FormatList(this IEnumerable<string> list, string returnMark = "-", char fg = ';')
        {
            var enumerable = list as string[] ?? list.ToArray();
            if (list == null || !enumerable.Any())
                return returnMark;
            var result = enumerable.Aggregate("", (current, s) => current + (s + fg));
            result = result.TrimEnd(fg);//.Substring(0,result.LastIndexOf(';'));
            return result;
        }

        /// <summary>
        /// <para> 功   能：防止sql注入 </para>
        /// <para> 作   者：韩保新</para>
        /// <para> 创建日期：2012/3/30</para>
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static string FormatSql(this string strValue)
        {
            if (string.IsNullOrEmpty(strValue))
                return "";
            const string sqlStr = "declare |exec |varchar |cursor |begin |open |drop |creat |select |truncate ";
            var sqlStrs = sqlStr.Split('|');
            var strValueLower = strValue.ToLower();
            foreach (string ss in sqlStrs)
            {
                if (strValueLower.ToLower().IndexOf(ss, StringComparison.Ordinal) >= 0)
                {
                    return strValue.Remove(strValue.ToLower().IndexOf(ss, StringComparison.Ordinal), ss.Length);
                }
            }
            return strValue.Replace("'", "''");
        }
        #endregion
    }
}
